import {
  Component,
  OnInit,
  Input,
  ChangeDetectorRef,
} from '@angular/core';
import { OverlayEntry, composePositionSet, Direction, HorizontalShowHideAnimation, VerticalShowHideAnimation } from '../shared/shared';

@Component({
  selector: 'fui-dropdown',
  templateUrl: './dropdown.component.html',
  animations: [
    HorizontalShowHideAnimation,
    VerticalShowHideAnimation,
  ],
})
export class DropdownComponent extends OverlayEntry implements OnInit {

  /** Direction to expand dropdown. */
  @Input() direction: Direction = 'bottom';

  /** Show caret triangle or not. */
  @Input() caret = true;

  /** Trigger method. */
  @Input() trigger: 'hover' | 'click' | 'context' = 'click';

  /** Append custom class to dropdown body for style customization. */
  @Input() customClass: string;

  /** Whether clicking dropdown will hide it or not. */
  @Input() clickHide = true;

  private openValue: boolean;
  /** Manually open or hide dropdown. */
  @Input()
  set open(value: boolean) {
    if (value) {
      this.openValue = true;
      this.show();
    } else {
      this.openValue = false;
      this.hide();
    }
  }
  get open(): boolean {
    return this.openValue;
  }

  classMap = {};

  get isHorizontal(): boolean {
    const directionFirstWord = this.direction[0];
    return directionFirstWord === 'l' || directionFirstWord === 'r';
  }

  get hasBackdrop() {
    return this.trigger === 'click';
  }

  constructor(
    private changeDetectionRef: ChangeDetectorRef,
  ) {
    super();
  }

  ngOnInit() {
    this.positions = composePositionSet(this.direction);
    this.setPosition(this.direction);
  }

  setPosition(direction: Direction) {
    this.classMap = {
      'fui-dropdown-has-caret': this.caret,
      [`fui-dropdown-${this.toShortDirection(direction)}`]: true,
    };
    if (this.customClass) {
      this.classMap[this.customClass] = true;
    }

    // 基于某些原因重渲染失败，需要手动触发。在其他项目Angular6.0 + CDK6.0无此问题.
    // TODO: 升级6.0之后移除
    this.changeDetectionRef.detectChanges();
  }

  toShortDirection(direction: string) {
    const dirSnakes = this.toSnake(direction);
    return dirSnakes.split('-')[0];
  }

  clickDropdown($event) {
    $event.stopPropagation();

    if (this.clickHide) {
      this.hide();
    }
  }

  mouseLeave() {
    if (this.trigger === 'hover') {
      this.hide();
    }
  }
}
